<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="优惠券名称" prop="couponName">
        <el-input
          v-model="queryParams.couponName"
          placeholder="请输入优惠券名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="优惠券类型" prop="couponType">
        <el-select v-model="queryParams.couponType" placeholder="请选择优惠券类型" clearable>
          <el-option
            v-for="dict in dict.type.ec_coupon_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发布状态" prop="publishStatus">
        <el-select v-model="queryParams.publishStatus" placeholder="请选择发布状态" clearable>
          <el-option
            v-for="dict in dict.type.ec_publish_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fun:allCoupon:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['fun:allCoupon:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fun:allCoupon:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fun:allCoupon:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="allCouponList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="优惠券ID" align="center" prop="couponId" />
      <el-table-column label="优惠券名称" align="center" prop="couponName" />
      <el-table-column label="优惠券类型" align="center" prop="couponType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ec_coupon_type" :value="scope.row.couponType"/>
        </template>
      </el-table-column>
      <el-table-column label="优惠金额" align="center" prop="couponAmount" />
      <el-table-column label="折扣率" align="center" prop="discountRate" />
      <el-table-column label="最低消费金额" align="center" prop="minAmount" />
      <el-table-column label="最高优惠金额" align="center" prop="maxAmount" />
      <el-table-column label="发行总数" align="center" prop="totalCount" />
      <el-table-column label="已使用数量" align="center" prop="usedCount" />
      <el-table-column label="已领取数量" align="center" prop="receiveCount" />
      <el-table-column label="生效时间" align="center" prop="enableTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.enableTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="失效时间" align="center" prop="expireTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expireTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布状态" align="center" prop="publishStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ec_publish_status" :value="scope.row.publishStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="使用说明" align="center" prop="note" width="200">
        <template slot-scope="scope">
          <div style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" :title="scope.row.note">
            {{ scope.row.note }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fun:allCoupon:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fun:allCoupon:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠券对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="优惠券名称" prop="couponName">
          <el-input v-model="form.couponName" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="couponType">
          <el-select v-model="form.couponType" placeholder="请选择优惠券类型" @change="handleCouponTypeChange">
            <el-option
              v-for="dict in dict.type.ec_coupon_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 优惠金额：满减券(1)和无门槛券(3)显示，折扣券(2)隐藏 -->
        <el-form-item label="优惠金额" prop="couponAmount" v-if="form.couponType != '2'">
          <el-input v-model="form.couponAmount" placeholder="请输入优惠金额" type="number" />
        </el-form-item>
        <!-- 折扣率：折扣券(2)显示，满减券(1)和无门槛券(3)隐藏 -->
        <el-form-item label="折扣率" prop="discountRate" v-if="form.couponType == '2'">
          <el-input v-model="form.discountRate" placeholder="请输入折扣率" type="number" />
        </el-form-item>
        <!-- 最低消费金额：满减券(1)和折扣券(2)显示，无门槛券(3)隐藏 -->
        <el-form-item label="最低消费金额" prop="minAmount" v-if="form.couponType != '3'">
          <el-input v-model="form.minAmount" placeholder="请输入最低消费金额" type="number" />
        </el-form-item>
        <!-- 最高优惠金额：折扣券(2)显示，满减券(1)和无门槛券(3)隐藏 -->
        <el-form-item label="最高优惠金额" prop="maxAmount" v-if="form.couponType == '2'">
          <el-input v-model="form.maxAmount" placeholder="请输入最高优惠金额" type="number" />
        </el-form-item>
        <el-form-item label="发行总数" prop="totalCount">
          <el-input v-model="form.totalCount" placeholder="请输入发行总数" type="number" />
        </el-form-item>
        <el-form-item label="已使用数量" prop="usedCount">
          <el-input v-model="form.usedCount" placeholder="请输入已使用数量" type="number" />
        </el-form-item>
        <el-form-item label="已领取数量" prop="receiveCount">
          <el-input v-model="form.receiveCount" placeholder="请输入已领取数量" type="number" />
        </el-form-item>
        <el-form-item label="生效时间" prop="enableTime">
          <el-date-picker clearable
            v-model="form.enableTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择生效时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="失效时间" prop="expireTime">
          <el-date-picker clearable
            v-model="form.expireTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择失效时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发布状态" prop="publishStatus">
          <el-radio-group v-model="form.publishStatus">
            <el-radio
              v-for="dict in dict.type.ec_publish_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="使用说明" prop="note">
          <el-input v-model="form.note" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAllCoupon, getAllCoupon, delAllCoupon, addAllCoupon, updateAllCoupon } from "@/api/fun/allCoupon"

export default {
  name: "AllCoupon",
  dicts: ['ec_publish_status', 'ec_coupon_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 优惠券表格数据
      allCouponList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        couponName: null,
        couponType: null,
        couponAmount: null,
        discountRate: null,
        minAmount: null,
        maxAmount: null,
        totalCount: null,
        usedCount: null,
        receiveCount: null,
        enableTime: null,
        expireTime: null,
        publishStatus: null,
        note: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        couponName: [
          { required: true, message: "优惠券名称不能为空", trigger: "blur" }
        ],
        couponType: [
          { required: true, message: "优惠券类型不能为空", trigger: "change" }
        ],
        totalCount: [
          { required: true, message: "发行总数不能为空", trigger: "blur" }
        ],
        enableTime: [
          { required: true, message: "生效时间不能为空", trigger: "blur" }
        ],
        expireTime: [
          { required: true, message: "失效时间不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询优惠券列表 */
    getList() {
      this.loading = true
      listAllCoupon(this.queryParams).then(response => {
        this.allCouponList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        couponId: null,
        couponName: null,
        couponType: null,
        couponAmount: null,
        discountRate: null,
        minAmount: null,
        maxAmount: null,
        totalCount: null,
        usedCount: null,
        receiveCount: null,
        enableTime: null,
        expireTime: null,
        publishStatus: null,
        note: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.couponId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // 设置默认优惠券类型为满减券
      this.form.couponType = '1'
      this.open = true
      this.title = "添加优惠券"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const couponId = row.couponId || this.ids
      getAllCoupon(couponId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改优惠券"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.couponId != null) {
            updateAllCoupon(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addAllCoupon(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const couponIds = row.couponId || this.ids
      this.$modal.confirm('是否确认删除优惠券编号为"' + couponIds + '"的数据项？').then(function() {
        return delAllCoupon(couponIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fun/allCoupon/export', {
        ...this.queryParams
      }, `allCoupon_${new Date().getTime()}.xlsx`)
    },
    /** 优惠券类型变化处理 */
    handleCouponTypeChange(value) {
      // 根据优惠券类型清空不相关的字段
      if (value == '1') {
        // 满减券：清空折扣率和最高优惠金额
        this.form.discountRate = null
        this.form.maxAmount = null
      } else if (value == '2') {
        // 折扣券：清空优惠金额
        this.form.couponAmount = null
      } else if (value == '3') {
        // 无门槛券：清空最高优惠金额、最低消费金额、折扣率
        this.form.maxAmount = null
        this.form.minAmount = null
        this.form.discountRate = null
      }
    }
  }
}
</script>
